package initialization

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/blog/config"
	"github.com/blog/database"
	"github.com/blog/internal/component"
	"github.com/blog/internal/container"
	"go.uber.org/zap"
)

// 全局容器实例
var Container container.Container

func init() {
	//初始化日志
	loggger, _ := zap.NewDevelopment()
	zap.ReplaceGlobals(loggger)
	wd, _ := os.Getwd()
	appConfig, err := config.LoadConfig(filepath.Join(wd, "config/app_config.yaml"))
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println(appConfig)

	db, err := database.InitMysql(appConfig)
	if err != nil {
		fmt.Println("数据库初始化链接失败...")
		zap.S().Error("数据库初始化链接失败...", err)
		return
	}
	fmt.Println("InitMysql成功")
	component.InitJwtManager(appConfig.Jwt.SecretKey, appConfig.Jwt.ExpireHour)
	//redis
	redisClient, err := component.InitRedis(appConfig.Redis.Host, appConfig.Redis.Port, appConfig.Redis.Auth)
	if err != nil {
		zap.S().Warnf("Redis连接失败: %v, 继续启动但Redis功能不可用", err)
		redisClient = nil
	} else {
		defer redisClient.Close()
	}

	//数据库和缓存展示全局管理
	Container = container.Container{}
	Container.SetAppConfig(appConfig)
	Container.SetDbInstance(db)
	Container.SetRedisInstance(redisClient)

}
